package com.demo.webflux.mongotx;

import java.time.Duration;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.demo.webflux.mongotx.TransactionWalletService.TxResult;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

@RestController
public class WalletController {

	private static Logger logger = LoggerFactory.getLogger(WalletController.class);
	@Autowired
	private TransactionWalletService transactionWalletService;
	private Random rnd = new Random(7);

	// 先初始化数据
	@GetMapping("/transfer")
	public Flux<TxResult> transfer(){
		return Flux.range(0, 1000) // 模拟1000次转账操作
			.flatMap(i -> Mono.delay(Duration.ofMillis(rnd.nextInt(10))) // 使用随机，激发事务竞争
					.publishOn(Schedulers.newParallel("test")) // 事务在新线程上运行，它的并行性定义了可能发生的并发事务数。
					.flatMap(_i -> {
						String fromOwner = randomOwner(); // 随机选择钱包所有者，和要转账的金额
						String toOwner = randomOwnerExcept(fromOwner);
						int amount = randomTransferAmount();
						return transactionWalletService.transferMoney(Mono.just(fromOwner), Mono.just(toOwner), Mono.just(amount));
					}));
	}

	private String randomOwner() {
		return "a";
	}

	private String randomOwnerExcept(String fromOwner) {
		return "b";
	}

	private int randomTransferAmount() {
		return 10;
	}

}
